package com.yjlove.myplay.utils;

import java.util.Map;
import com.yjlove.myplay.AppContext;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * SharedPreferences帮助类
 */
public class SP {

	private static Context mContext = AppContext.getInstance();
	private static SharedPreferences sp;

	/**
	 * 保存信息
	 */
	public static void save(String key, Object object) {

		if (sp == null) {
			sp = mContext.getSharedPreferences("config", Context.MODE_PRIVATE);
		}
		SharedPreferences.Editor editor = sp.edit();
		if (object == null) {
			editor.putString(key, "NULL");
		} else if (object instanceof String) {
			editor.putString(key, (String) object);
		} else if (object instanceof Integer) {
			editor.putInt(key, (Integer) object);
		} else if (object instanceof Boolean) {
			editor.putBoolean(key, (Boolean) object);
		} else if (object instanceof Float) {
			editor.putFloat(key, (Float) object);
		} else if (object instanceof Long) {
			editor.putLong(key, (Long) object);
		} else {
			editor.putString(key, object.toString());
		}

		editor.commit();
	}

	/**
	 * 获取信息
	 */
	public static <T> T get(String key, T defaultObject) {

		if (sp == null) {
			sp = mContext.getSharedPreferences("config", Context.MODE_PRIVATE);
		}

		if (defaultObject instanceof String) {
			return (T) sp.getString(key, (String) defaultObject);
		} else if (defaultObject instanceof Integer) {
			return (T) (Object) sp.getInt(key, (Integer) defaultObject);
		} else if (defaultObject instanceof Boolean) {
			return (T) (Object) sp.getBoolean(key, (Boolean) defaultObject);
		} else if (defaultObject instanceof Float) {
			return (T) (Object) sp.getFloat(key, (Float) defaultObject);
		} else if (defaultObject instanceof Long) {
			return (T) (Object) sp.getLong(key, (Long) defaultObject);
		}

		return defaultObject;

	}

	/**
	 * 移除某个key值已经对应的值
	 *
	 * @param key
	 */
	public static void remove(String key) {
		if (sp == null) {
			sp = mContext.getSharedPreferences("config", Context.MODE_PRIVATE);
		}
		sp.edit().remove(key).commit();
	}

	/**
	 * 清除所有数据
	 */
	public static void clear() {

		if (sp == null) {

			sp = mContext.getSharedPreferences("config", Context.MODE_PRIVATE);
		}
		sp.edit().clear();

	}

	/**
	 * 查询某个key是否已经存在
	 * @param key
	 * @return
	 */
	public static boolean contains(String key) {
		if (sp == null) {

			sp = mContext.getSharedPreferences("config", Context.MODE_PRIVATE);
		}
		return sp.contains(key);
	}

	/**
	 * 返回所有的键值对
	 *
	 * @return
	 */
	public static Map<String, ?> getAll() {
		if (sp == null) {

			sp = mContext.getSharedPreferences("config", Context.MODE_PRIVATE);
		}
		return sp.getAll();
	}

}
